package dao;

import entity.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    private static PreparedStatement statement = null;
    private static ResultSet result = null;

    /**
     * 通过用户名和密码验证用户
     * @param userName 用户名称
     * @param password 用户密码
     * @return
     * @throws Exception
     */
    public static User getUser(String userName,String password) throws Exception {
        User user = null;
        String sql = "SELECT * FROM user WHERE user_name = " + userName + " and password = " + password;
        statement = DataBaseOperation.getConnectionAndStatement(sql,statement);
        result = statement.executeQuery();
        while(result.next()){
            user = new User(result.getInt("user_id"),result.getString("user_name"),result.getString("password"),
                    result.getInt("type"),result.getString("nickname"));
        }
        DataBaseOperation.close(result,statement);
        return user;
    }

    /**
     * 通过用户ID得到用户信息
     * @param userId 用户ID
     * @return
     * @throws SQLException
     */
    public static User getUser(String userId) throws SQLException {
        User user = null;
        String sql = "SELECT * FROM user WHERE user_id = " + userId;
        statement = DataBaseOperation.getConnectionAndStatement(sql,statement);
        result = statement.executeQuery();
        while(result.next()){
            user = new User(result.getInt("user_id"),result.getString("user_name"),result.getString("password"),
                    result.getInt("type"),result.getString("nickname"));
        }
        DataBaseOperation.close(result,statement);
        return user;
    }

    /**
     * 通过用户名查找用户是否存在
     * @param userName 需要查找的用户名
     * @return
     * @throws SQLException
     */
    public static boolean findUser(String userName) throws SQLException {
        User user = null;
        String sql = "SELECT * FROM user WHERE user_name = ?";
        statement = DataBaseOperation.getConnectionAndStatement(sql,statement);
        statement.setString(1,userName);
        result = statement.executeQuery();
        if(result.next() == false){
            return false;
        }
        DataBaseOperation.close(result,statement);
        return true;
    }

    /**
     * 注册用户
     * @param userName 用户名
     * @param password 用户密码
     * @param nickName 用户昵称
     * @return
     */
    public static int registerUser(String userName, String password, String nickName)  {
        int result = 0;
        String sql = "INSERT INTO user(user_name,password,type,nickname) VALUES("+ userName + "," + password + ",0," + nickName + ")";
        try {
            statement = DataBaseOperation.getConnectionAndStatement(sql,statement);
            result = statement.executeUpdate();
            DataBaseOperation.close(statement);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

}
